package com.example.dangerouscargodriver;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.Application;
import android.content.Context;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
import android.util.Log;

import com.example.dangerouscargodriver.controller.AreaInfoController;
import com.example.dangerouscargodriver.controller.AttrInfoController;
import com.example.dangerouscargodriver.controller.AuthController;
import com.example.dangerouscargodriver.controller.BankAccountInfoController;
import com.example.dangerouscargodriver.controller.EnterPlatformInfoController;
import com.example.dangerouscargodriver.controller.PaySetInfoController;
import com.example.dangerouscargodriver.controller.UserInfoController;
import com.example.dangerouscargodriver.service.LocationService;
import com.baidu.mapapi.CoordType;
import com.baidu.mapapi.SDKInitializer;

import com.xiaomi.channel.commonutils.logger.LoggerInterface;
import com.xiaomi.mipush.sdk.Logger;
import com.xiaomi.mipush.sdk.MiPushClient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

/**
 * 1、为了打开客户端的日志，便于在开发过程中调试，需要自定义一个 Application。
 * 并将自定义的 application 注册在 AndroidManifest.xml 文件中。<br/>
 * 2、为了提高 push 的注册率，您可以在 Application 的 onCreate 中初始化 push。你也可以根据需要，在其他地方初始化 push。
 *
 * @author wangkuiwei
 */
public class DangerousCargoDriverApplication extends Application {

    private static final int MSG_CHECK_LOGIN = 1;
    private static final int MSG_ICON_DOWNLOAD = 2;

    // user your appid the key.
    private static final String APP_ID = "2882303761520027733";
    // user your appid the key.
    private static final String APP_KEY = "5702002723733";

    // 此TAG在adb logcat中检索自己所需要的信息， 只需在命令行终端输入 adb logcat | grep
    // com.xiaomi.mipushdemo
    public static final String TAG = "Application";

    private static DemoHandler sHandler = null;
    private static MainActivity sMainActivity = null;

    public LocationService locationService;

    private static  Context mContext = null;

    public static Context getAppContext(){
        return  mContext;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        // 注册push服务，注册成功后会向DemoMessageReceiver发送广播
        // 可以从DemoMessageReceiver的onCommandResult方法中MiPushCommandMessage对象参数中获取注册信息
        if (shouldInit()) {
            Log.d(TAG, "registerPush");
            MiPushClient.registerPush(this, APP_ID, APP_KEY);
        }

        LoggerInterface newLogger = new LoggerInterface() {

            @Override
            public void setTag(String tag) {
                // ignore
            }

            @Override
            public void log(String content, Throwable t) {
                Log.d(TAG, content, t);
            }

            @Override
            public void log(String content) {
                Log.d(TAG, content);
            }
        };
        Logger.setLogger(this, newLogger);
        if (sHandler == null) {
            sHandler = new DemoHandler(this);
        }

        /***
         * 初始化定位sdk，建议在Application中创建
         */
        locationService = new LocationService(getApplicationContext());
        SDKInitializer.initialize(getApplicationContext());
        SDKInitializer.setCoordType(CoordType.BD09LL);

        mContext = getApplicationContext();

        //创建缓存目录，系统一运行就得创建缓存目录的，
        File cache = new File(Environment.getExternalStorageDirectory(), "vsiji/Pictures");

        if(!cache.exists()){
            cache.mkdirs();
        }

        AreaInfoController.Instance();
        UserInfoController.Instance();
        AuthController.Instance();
        AttrInfoController.Instance();
        PaySetInfoController.Instance();
        EnterPlatformInfoController.Instance();
        BankAccountInfoController.Instance();
    }

    private boolean shouldInit() {
        ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE));
        List<RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = getPackageName();
        int myPid = Process.myPid();
        for (RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }

    public static DemoHandler getHandler() {
        return sHandler;
    }

    public static class DemoHandler extends Handler {

        WeakReference<DangerousCargoDriverApplication> mApplication;

        public DemoHandler(DangerousCargoDriverApplication application) {
            this.mApplication = new WeakReference<DangerousCargoDriverApplication>(application);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                default:
                    break;
            }

        }
    }

    /*
     * 从网络上获取图片，如果图片在本地存在的话就直接拿，如果不存在再去服务器上下载图片
     * 这里的path是图片的地址
     */
    public Uri getImageURI(String path, File cache) throws Exception {
        String name = path.substring(path.lastIndexOf("."));
        File file = new File(cache, name);
        // 如果图片存在本地缓存目录，则不去服务器下载
        if (file.exists()) {
            return Uri.fromFile(file);//Uri.fromFile(path)这个方法能得到文件的URI
        } else {
            // 从网络上获取图片
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            if (conn.getResponseCode() == 200) {

                InputStream is = conn.getInputStream();
                FileOutputStream fos = new FileOutputStream(file);
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }
                is.close();
                fos.close();
                // 返回一个URI对象
                return Uri.fromFile(file);
            }
        }

        return null;
    }
}